package com.xjc.system.handler;

import com.xjc.system.exception.MyException;
import com.xjc.system.result.Result;
import com.xjc.system.result.ResultCode;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 徐锦程
 * 时间:2024-10-01 15:39
 * 描述:全局异常处理类
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 其他异常
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Result> handleException(Exception ex) {

        ex.printStackTrace();

        Result errorResponse = Result.builder().code(ResultCode.INTERNAL_SERVER_ERROR.getCode()).message(ResultCode.INTERNAL_SERVER_ERROR.getMessage()).build();

        return new ResponseEntity<>(errorResponse, HttpStatus.resolve(ResultCode.SUCCESS.getCode()));
    }

    /**
     * 主动抛错
     * @param ex e
     * @return r
     */
    @ExceptionHandler(MyException.class)
    public ResponseEntity<Result> handleException(MyException ex) {

        Result errorResponse = Result.builder().code(ex.getCode()).message(ex.getMessage()).build();

        return new ResponseEntity<>(errorResponse, HttpStatus.resolve(ResultCode.SUCCESS.getCode()));
    }
}
